/*
 * @Author: weidewei
 * @Date: 2025-11-19 15:39:51
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-24 10:34:09
 * @Description: 
 * @FilePath: \2025-front-face\vite-react-ts-template\src\pages\useState.tsx
 */
/*
 * @Author: weidewei
 * @Date: 2025-11-19 15:39:51
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-20 09:25:12
 * @Description:
 * @FilePath: \2025-front-face\vite-react-ts-template\src\pages\useState.tsx
 */
import { useState } from 'react';
import styled from 'styled-components';
const family = [
  {
    name: '儿子',
    age: 18,
  },
  {
    name: '爸爸',
    age: 38,
  },
];
export default function useStateComp() {
  const [count, setCount] = useState(0);
  const [familyState,setFamily] = useState(family);
  const [user, setUser] = useState({
    name: 'monica',
    sex: '男',
    addr: {
      city: '深圳',
    },
  });
  const [visible,setVisible] = useState(false);
  function handleChangeNum() {
    setCount(count + 1);
    // setCount(count+2);
    // console.log(count); // 这里输出的还是原来的值，不是变化后的值
  }

  function handleChangeNum1() {
    // setCount(count+1); // 直接传递状态，无法更新多次的值
    setCount((val) => val + 1); // 传递要执行的更新函数
  }

  function handleChangeSex() {
    // user.sex = '女'; // 直接改变对象，视图不更新
    setUser({
      ...user,
      sex: '女',
      addr: {
        city: '南宁',
      },
    });
    console.log(user);
  }

  function handleAddFamily() {
    setFamily([
        ...familyState,
        {
           name: '女儿',
           age: 5
        }
    ])
  }
  return (
    <Wrapper>
      <div className="state">
        <button onClick={handleChangeNum}>点击+1</button>
        <button
          onClick={() => {
            handleChangeNum1();
            handleChangeNum1();
            handleChangeNum1();
          }}
        >
          点击+3
        </button>
        <button onClick={handleChangeSex}>改变性别</button>
        <button onClick={handleAddFamily}>添加家庭成员</button>
        <button onClick={()=>setVisible(!visible)}>显示/隐藏元素</button>
        <p style={{display: visible ? 'block' : 'none'}}>计数数字：{count}</p>
        <p>
          我叫：{user.name}，性别是：{user.sex}，住在{user.addr.city}
        </p>
        家庭成员：
        <ul>
          {
            familyState.map(item=>(
                <li key={item.age}>{item.name}</li>
            ))
          }
        </ul>
      </div>
    </Wrapper>
  );
}
const Wrapper = styled.div`
  .state {
    color: blue;
  }
`;
